package com.yusp75.myexam.ui.books

import android.content.Context
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yusp75.myexam.com.yusp75.myexam.data.BookRepository
import com.yusp75.myexam.com.yusp75.myexam.util.ProgressState
import com.yusp75.myexam.data.Book
import com.yusp75.myexam.data.BookWithCounts
import com.yusp75.myexam.data.ExcelToRoomHelper
import com.yusp75.myexam.di.DataHolder
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import org.koin.mp.KoinPlatform.getKoin


class BookViewModel(
    private val holder: DataHolder,
    private val repository: BookRepository
) : ViewModel() {

    private lateinit var helper: ExcelToRoomHelper

    val books: Flow<List<BookWithCounts>> = repository.allBooks

    fun deleteBook(book: Book) = viewModelScope.launch {
        repository.deleteBook(book)
    }

    fun selectBook(book: Book) = viewModelScope.launch {
        repository.selectBook(holder.bookId, book)
        holder.bookId = book.id
    }

    private val _progressState = MutableStateFlow<ProgressState>(ProgressState.Pending)
    val progressState: StateFlow<ProgressState> = _progressState.asStateFlow()

    fun processFile(context: Context, file: String?, uri: Uri?) {
        helper = getKoin().get<ExcelToRoomHelper>()
        viewModelScope.launch {
            helper.writeToRoom(context, file, uri)
                .catch { e ->
                    _progressState.value = ProgressState.Error(e.message.toString())
                } // 异常处理
                .collect { state -> _progressState.value = state }
        }
    }

    //
}